<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input v-model="isAll" type="checkbox" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in goodList" :key="index">
          <td>
            <input
              v-model="item.checked"
              :value="item.num * item.price"
              type="checkbox"
            />
          </td>
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>
            <button @click="reduce(index)">-</button>
            {{ item.num }}
            <button @click="add(index)">+</button>
          </td>
          <td>{{ item.num * item.price }}</td>
          <td>
            <button @click="del(index)">删除</button>
          </td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:{{ total }}</td>
          <td colspan="5"></td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
export default {
  props: ['goodList'],
  data () {
    return {}
  },
  methods: {
    add (id) {
      this.goodList[id].num++
    },
    reduce (id) {
      if (this.goodList[id].num <= 0) return
      this.goodList[id].num--
    },
    del (id) {
      this.goodList.splice(id, 1)
    }
  },
  computed: {
    isAll: {
      set (val) {
        this.goodList.forEach(item => (item.checked = val))
      },
      get () {
        return this.goodList.every(item => item.checked)
      }
    },
    total () {
      let sum = 0
      this.goodList.forEach((item, index) => {
        if (item.checked) {
          sum += item.num * item.price
        }
      })
      return sum
    }
  }
}
</script>

<style lang="scss" scoped></style>
